//
//  WmcLogin.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/3/31.
//

import Foundation
import HandyJSON
import KeychainAccess
import YPBedrock
import YPNetwork

class WmcLoginManager {
    // Internal

    typealias WmcLoginInfo = (step: LoginStep, yupaoAccount: WmcYupaoAccountModel?, wmcAccount: WmcAccountModel?)
    
    enum LoginStep: Int {
        /// 未登录
        case logout
        /// 已登录鱼泡账号
        case firstStep
        /// 已获取水印相机数据
        case secondStep
    }

    static let shared = WmcLoginManager()

    /// 水印相机账号数据
    private(set) var wmcAccountModel: WmcAccountModel?

    /// 鱼泡账号数据
    private(set) var yupaoAccountModel: WmcYupaoAccountModel?

    /// 登录到第几步
    var loginStep: LoginStep {
        if yupaoAccountModel != nil, wmcAccountModel != nil {
            return .secondStep
        } else if yupaoAccountModel != nil {
            return .firstStep
        }

        return .logout
    }

    /// 是否登录
    var isLogin: Bool {
        return loginStep == .secondStep
    }
    
    static func config(completion: ((WmcLoginInfo) -> Void)? = nil) {
        /// 查询登录信息
        WmcLoginManager.queryLoginInfo { info in
            /// 查询结束回调
            completion?(info)
        }
    }
    
    static func loginHost() -> String {
        /*
         测试站 https://yupao-test.yupaowang.com
         预发布 https://yupao-master.kkbbi.com
         正式站 https://yupao-prod.54xiaoshuo.com
         预发布正式站 https://yupao-release.kkbbi.com
          */
        var host = "https://yupao-prod.54xiaoshuo.com"
        let environmentType = YPWmcManager.shared.environmentType

        if environmentType == .develop || environmentType == .test {
            host = "https://yupao-test.yupaowang.com"
        } else if environmentType == .pre_release {
            host = "https://yupao-master.kkbbi.com"
        }
        
        return host
    }

    /// 跳转到登录界面
    /// - Parameters:
    ///   - animated: 是否需要动画
    ///   - success: 登录成功
    ///   - failure: 登录失败
    static func push(animated: Bool, success: YPBlock.Empty? = nil, failure: YPBlock.Empty? = nil) {
        YPWmcManager.shared.delegate.loginDelegate?.loginNeed(.current, animated: animated, success: success, failure: failure)
    }

    /// 查询登录信息
    /// - Parameter completion: 查询回调
    static func queryLoginInfo(completion: ((WmcLoginInfo) -> Void)? = nil) {
        WmcUserInfoDBManager.query { data in
            guard let data = data else {
                WmcLoginManager.shared.yupaoAccountModel = nil
                WmcLoginManager.shared.wmcAccountModel = nil
                WmcPreferenceSettingsManager.cleanSyncCongig()

                let r: WmcLoginInfo = (step: LoginStep.logout, yupaoAccount: nil, wmcAccount: nil)
                completion?(r)
                return
            }
            
            var ypAccountModel: WmcYupaoAccountModel?
            var wmcAccountModel: WmcAccountModel?
            if let yupaoAccount = data["yupao_userInfo"] as? String {
                ypAccountModel = WmcYupaoAccountModel.deserialize(from: yupaoAccount)

                if let wmcAccount = data["wmc_userInfo"] as? String {
                    wmcAccountModel = WmcAccountModel.deserialize(from: wmcAccount)
                }
            }

            WmcLoginManager.shared.yupaoAccountModel = ypAccountModel
            WmcLoginManager.shared.wmcAccountModel = wmcAccountModel

            let r: WmcLoginInfo = (step: WmcLoginManager.shared.loginStep, yupaoAccount: ypAccountModel, wmcAccount: wmcAccountModel)
            completion?(r)
        }
    }

    ///  设置鱼泡账号信息
    /// - Parameters:
    ///   - userInfo: 账号信息
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func setYupaoAccountModel(userInfo: [String: String],
                                     success: (() -> Void)? = nil,
                                     failure: ((YPNetworkError?) -> Void)? = nil) {
        Self.queryLoginInfo { model in
            if let ypAccountModel = model.yupaoAccount, ypAccountModel.userId == userInfo["uid"] {
                return
            }
            
            var params: [String: String] = [:]
            params["uid"] = userInfo["uid"]
            params["uuid"] = userInfo["uuid"]
            params["token"] = userInfo["token"]
            params["singletoken"] = userInfo["singleSignToken"]
            params["userId"] = userInfo["uid"]
            params["userName"] = userInfo["username"]
            params["nickName"] = userInfo["nickname"]
            params["phone"] = userInfo["tel"]
            params["userType"] = userInfo["type"]
            params["errcode"] = userInfo["errCode"]
            
            WmcLoginManager.shared.fetchWmcUserInfo(userInfo: params, success: success, failure: failure)
        }
    }
    
    /// 设置鱼泡账号信息（开放给其他平台注册登录使用）
    /// - Parameters:
    ///   - userModel: 用户信息
    ///   - success: 成功回调
    ///   - failure: 失败回调
    static func setYupaoAccountModel(userModel: WmcYupaoAccountProtocol,
                                     success: (() -> Void)? = nil,
                                     failure: ((YPNetworkError?) -> Void)? = nil) {
        Self.queryLoginInfo { model in
            if let ypAccountModel = model.yupaoAccount, ypAccountModel.userId == userModel.userId {
                return
            }
            
            var params: [String: String] = [:]
            params["uid"] = userModel.userId
            params["uuid"] = userModel.uuid
            params["token"] = userModel.token
            params["singletoken"] = userModel.singletoken
            params["userId"] = userModel.userId
            params["userName"] = userModel.userName
            params["nickName"] = userModel.nickName
            params["phone"] = userModel.phone
            params["userType"] = userModel.userType
            params["errcode"] = userModel.errcode
            
            WmcLoginManager.shared.fetchWmcUserInfo(userInfo: params, success: success, failure: failure)
        }
    }

    /// 退出登录
    static func logout() {
        WmcUserInfoDBManager.delete { result in
            if result {
                WmcLoginManager.shared.yupaoAccountModel = nil
                WmcLoginManager.shared.wmcAccountModel = nil
                WmcPreferenceSettingsManager.cleanSyncCongig()
                WmcUploadQueueManager.stopAllTask()
            }
        }
    }
    
    /// 静默登录
    /// - Parameters:
    ///   - phone: 手机号
    ///   - password: 密码
    static func silentLogin(phone: String, password: String) {
        let host = Self.loginHost()
        WmcUserCenterAPI.loginYupaoAccount(host: host, phone: phone, password: password) { data in
            
        } failure: { error in
            
        }
    }
    
    /// 更新用户信息
    /// - Parameters:
    ///   - name: 姓名
    ///   - phone: 手机号
    ///   - completion: 回调
    static func updateUserInfo(name: String? = nil, phone: String? = nil, completion: ((Bool) -> Void)? = nil) {
        guard var yupaoAccountModel = WmcLoginManager.shared.yupaoAccountModel, var wmcAccountModel = WmcLoginManager.shared.wmcAccountModel else {
            completion?(false)
            return
        }
        
        if let name = name, !name.isEmpty {
            wmcAccountModel.name = name
        }
        
        if let phone = phone, !phone.isEmpty {
            yupaoAccountModel.phone = phone
            wmcAccountModel.phone = phone
        }
        
        let yupaoAccountInfo = yupaoAccountModel.toJSON()
        let wmcAccountInfo = wmcAccountModel.toJSON()
        
        WmcUserInfoDBManager.update(wmcUserInfo: wmcAccountInfo, yupaoUserInfo: yupaoAccountInfo) { isSuccess in
            if isSuccess {
                WmcLoginManager.shared.yupaoAccountModel = yupaoAccountModel
                WmcLoginManager.shared.wmcAccountModel = wmcAccountModel
            }
            
            completion?(isSuccess)
        }
    }
    
    static func checkLogin(_ successBlock: @escaping YPBlock.Empty) {
        if !WmcLoginManager.shared.isLogin {
            if YPWmcManager.shared.isIndependentPage {
                WmcLoginManager.push(animated: true) {
                    successBlock()
                } failure: {
                    WmcHudManager.toast("登录失败")
                }
            } else {
                YPWmcManager.shared.delegate.loginDelegate?.loginNeed(.current, animated: true, success: {
                    successBlock()
                }, failure: {
                    WmcHudManager.toast("登录失败")
                })
            }
        } else { // 已登录
            successBlock()
        }
    }

    // Private

    /// 获取水印相机token
    /// - Parameters:
    ///   - success: 获取成功
    ///   - failure: 获取失败
    func fetchWmcUserInfo(userInfo: [String: String], silent: Bool = true, success: (() -> Void)? = nil, failure: ((YPNetworkError?) -> Void)? = nil) {
        
        if !silent {
            WmcHudManager.loading()
        }
        WmcMediaUserCenterAPI.fetchAccountInfo(userInfo: userInfo) { [weak self] info in
            guard let weakSelf = self else { return }
            if !silent {
                WmcHudManager.dismiss()
            }
            guard let yupaoAccountModel = WmcYupaoAccountModel.deserialize(from: userInfo),
                  let jsonDic = yupaoAccountModel.toJSON(),
                  let wmcAccountModel = WmcAccountModel.deserialize(from: info) else
            {
                return
            }
            weakSelf.yupaoAccountModel = yupaoAccountModel
            weakSelf.wmcAccountModel = wmcAccountModel
            
            WmcUserInfoDBManager.save(yupaoUserInfo: jsonDic, wmcUserInfo: info) { isSuccess in
                WmcDBManager.shared.createUploadQueueTable()
                WmcDBManager.shared.createUploadQueueV2Table()
                WmcDBManager.shared.createCloudAblumInfoTable()
                success?()
            }
        } failure: { error in
            if !silent {
                WmcHudManager.dismiss()
            }
            failure?(error)
        }
    }
    
    /// 检测是否已登录,如果未登录则进行登录
    /// - Parameter successed: 登录成功回调
    /// - Returns: 登录状态
    static func checkLogin(successed: (() -> Void)? = nil) -> Bool {
        if shared.isLogin {
            return true
        }
        WmcLoginManager.push(animated: true) {
            WmcHudManager.toast("登录成功")
            successed?()
        } failure: {
            WmcHudManager.toast("登录失败")
        }
        return false
    }
}

extension WmcLoginManager {
    
    func updateLocalAvatarUrl(url: String) -> Void {
        self.wmcAccountModel?.avatar = url
    }
}
